<template>
  <drawer 
    :show="show" 
    :title="title"
    :showBtns="true"
    :confirmText="comfireText"
    :cancelText="'重置'"
    @cancel="handleReset"
    @confirm="submit"
    @close="bindClose"
  >
    <!-- 电梯详情页面显示 -->
    <view class="elevator-info" v-if="Object.keys(isFilterList).length">
      <view class="elevator-info-item">
        <image src="/static/images/index/itemPro.png" class="elevator-icon" />
        <text>{{ isFilterList.buildingName || isFilterList.name }}</text>
      </view>
      <view class="elevator-info-item" v-if="isFilterList.elevatorAddress">
        <image src="/static/images/index/total.png" class="elevator-icon" />
        <text>{{ isFilterList.elevatorAddress }}</text>
      </view>
    </view>

    <!-- 完成时间选择日期 -->
    <view v-if="isShowDate">
      <date-filter 
        v-if="isShowDate" 
        :title="['计划时间', '报障时间', '申请时间', '创建时间', '创建时间', '创建时间','计划时间'][orderType]"
        @getDate="getDate2" 
        option-key="date-filter2" 
        :isResetDate="isResetDate2"
        ref="date-filter2" 
        :dateObj="dateObj"
      />
      <date-filter 
        v-if="isShowDate" 
        @getDate="getDate" 
        option-key="date-filter" 
        :isResetDate="isResetDate"
        ref="date-filter" 
        :dateObj="dateObj"
        :title="['维保签字时间', '完成时间', '完成时间', '完成时间', '完成时间', '完成时间', '完成时间'][orderType]"
      />
    </view>

    <!-- 筛选选项 -->
    <view v-for="(item, index) in filterList" :key="index">
      <filter-item
        v-if="fitlerContract(item)"
        :show="true"
        :label="item.title"
        :options="formatFilterOptions(item.list)"
        :value="choosed[item.key] || []"
        :multiple="item.key !== 'scoreStatus'"
        @input="(value) => handleFilterChange(item.key, value)"
        @change="(value) => handleFilterChange(item.key, value)"
      />
    </view>

    <!-- 保养排期计划选择日期 -->
    <view v-if="isMainPlan">
      <date-filter 
        :isMainPlan="isMainPlan" 
        :mainTips="mainTips" 
        :title="['计划时间'][0]"
        @getDate="getDate2" 
        option-key="date-filter2" 
        :isResetDate="isResetDate2"
        :dateList="dateLists" 
        ref="date-filter2" 
        :dateObj="dateObj" 
        hide-time-range
        @customerOpenTime="customerOpenTime"
      >
        <template v-slot:bottom>
          <slot name="dateFilterBottom"></slot>
        </template>
      </date-filter>
    </view>

    <!-- 保养模板 -->
    <view v-if="isShowTemplate">
      <task-filter 
        @chooseTemp="chooseTemp"
        ref="task-filter"
      />
    </view>

    <!-- 配件筛选 -->
    <view v-if="isShowPart">
      <pj-filter 
        @choosePart="choosePart" 
        ref="pj-filter"
      />
    </view>
  </drawer>
</template>

<script>
import Drawer from './drawer.vue';
import FilterItem from './filter-item.vue';
import DateFilter from './dateFilter';
import PjFilter from './pjFilter';
import TaskFilter from '@/components/filter-drawer/taskFilter.vue';

export default {
	components: {
		Drawer,
		FilterItem,
		DateFilter,
		TaskFilter,
		PjFilter,
	},
	name: 'filter-drawer',
	data() {
		return {
			choosed: {},
			allChecked: false,
			showMap: {},
			dateObj: {},
			isResetDate: false,
			isResetDate2: false,
			scrollTop: 0,
			chooseTime: {
				planBeginDate: '',
				planEndDate: '',
				startTime: '',
				endTime: '',
				value: '',
				value2: '',
			},
		};
	},
	props: {
		chooseData: {
			type: [Object, Array],
			default: () => {
				return {};
			},
		},
		// 个人工单 新增时间筛选
		orderType: {
			type: Number,
			default: 0,
		},
		border: {
			// 是否显示边框
			type: Boolean,
			default: false,
		},
		filterList: {
			type: Array,
			default: () => {
				return [];
			},
		},
		show: {
			type: Boolean,
			default: true,
		},
		comfireText: {
			type: String,
			default: '确认',
		},
		keyMap: {
			type: Object,
			default: () => {
				return {};
			}
		},
		// 标题的名字
		title: {
			type: String,
			default: '筛选',
		},
		isShowDate: {
			type: Boolean,
			default: false,
		},
		isShowTemplate: {
			type: Boolean,
			default: false,
		},
		isShowPart: {
			type: Boolean,
			default: false,
		},
		// 项目保养计划
		isMainPlan: {
			type: Boolean,
			default: false,
		},
		dateLists: {
			type: Array,
			default: () => [],
		},
		mainTips: {
			type: String,
			default: '',
		},
		// 电梯详情页面
		isFilterList: {
			type: Object,
			default: () => {
				return {};
			},
		},
		countState: {
			// 保养月历计划页面
			type: Number,
			default: 0,
		},
	},
	watch: {
		keyMap(val) {
			this.showMap = val;
		},
		filterList(val) {
		},
		show(val) {
			if (val) {
				this.scrollTop = 1;
				this.$nextTick(() => {
					this.scrollTop = 0;
				});
			}
		},
	},
	created() {
		this.choosed = this.chooseData;
	},
	methods: {
		// 格式化筛选选项
		formatFilterOptions(list) {
			return list.map(item => ({
				label: item.name,
				value: item.value
			}));
		},

		// 处理筛选选项变化
		handleFilterChange(key, value) {
			// 如果是全选全选关闭
			if (this.allChecked) {
				this.allChecked = false;
			}

			// 评分状态 单选
			if (key == 'scoreStatus') {
				if (this.choosed[key] && this.choosed[key].includes(value)) {
					delete this.choosed[key];
				} else {
					this.choosed[key] = [value];
				}
			} else {
				this.choosed[key] = value;
			}

			if (key == 'useTypes' && this.isMainPlan) {
				// 保养计划月历
				this.choosed[key] = [value];
			}
      
			this.$forceUpdate();

			this.$emit('chooseTag', {
				allChecked: this.allChecked,
				choosed: this.choosed,
				...this.chooseTime,
			});
		},

		// 保养月历页面
		customerOpenTime(obj) {
			this.$emit('customerOpenTime', obj);
		},

		choosePart(res) {
			let partsId = res.map((item) => {
				return item.id;
			});

			this.choosed.partsId = partsId;
			this.$emit('chooseTag', {
				allChecked: this.allChecked,
				choosed: this.choosed,
				...this.chooseTime,
			});
		},

		// 获取模板选择
		chooseTemp(res) {
			let templateIds = res.map((item) => {
				return item.id;
			});

			this.choosed.templateIds = templateIds;
			this.$emit('chooseTag', {
				allChecked: this.allChecked,
				choosed: this.choosed,
				...this.chooseTime,
			});
		},

		// 获取首位时间
		getOtherDate(res) {
			this.chooseTime.planBeginDate = res.startTime;
			this.chooseTime.planEndDate = res.endTime;
			this.$emit('chooseTag', {
				allChecked: this.allChecked,
				choosed: this.choosed,
				planBeginDate: res.startTime,
				planEndDate: res.endTime,
				startTime: this.chooseTime.startTime,
				endTime: this.chooseTime.endTime,
			});
		},

		// 获取选择的时间
		getDate(res) {
			this.chooseTime.startTime = res.startTime;
			this.chooseTime.endTime = res.endTime;
			this.chooseTime.value = res.value;
			this.$emit('chooseTag', {
				allChecked: this.allChecked,
				choosed: this.choosed,
				startTime: res.startTime,
				endTime: res.endTime,
				planBeginDate: this.chooseTime.planBeginDate,
				planEndDate: this.chooseTime.planEndDate,
			});
		},

		// 获取选择计划的时间
		getDate2(res) {
			console.log(res, '获取时间');
			// 处理后6个月和本年选项
			if (res.value === 8 || res.value === 9) {
				const now = new Date();
				if (res.value === 8) { // 后6个月
					// 从下月1日开始到6个月后的月末
					const startDate = new Date(now.getFullYear(), now.getMonth() + 1, 1);
					const endDate = new Date(now.getFullYear(), now.getMonth() + 7, 0);

					// 格式化日期
					this.chooseTime.planBeginDate = this.formatDate(startDate);
					this.chooseTime.planEndDate = this.formatDate(endDate);
				} else if (res.value === 9) { // 本年
					// 本年1月1日到12月31日
					const startDate = new Date(now.getFullYear(), 0, 1);
					const endDate = new Date(now.getFullYear(), 11, 31);

					// 格式化日期
					this.chooseTime.planBeginDate = this.formatDate(startDate);
					this.chooseTime.planEndDate = this.formatDate(endDate);
				}
				this.chooseTime.value2 = res.value;
			} else {
				this.chooseTime.planBeginDate = res.startTime;
				this.chooseTime.planEndDate = res.endTime;
				this.chooseTime.value2 = res.value;
			}
			let chooseTime = JSON.parse(JSON.stringify(this.chooseTime));
			console.log(res, 'res.startTime');
			this.$emit('chooseTag', {
				allChecked: this.allChecked,
				choosed: this.choosed,
				planBeginDate: chooseTime.planBeginDate,
				planEndDate: chooseTime.planEndDate,
				startTime: chooseTime.startTime,
				endTime: chooseTime.endTime,
				cuValue: res.value,
			});
		},

		// 格式化日期的辅助方法
		formatDate(date) {
			const year = date.getFullYear();
			const month = (date.getMonth() + 1).toString().padStart(2, '0');
			const day = date.getDate().toString().padStart(2, '0');
			return `${year}-${month}-${day}`;
		},

		doNothing() {
		},

		fitlerContract(item) {
			let flag = true;
			if (item.key == 'contractStatus') {
				flag = this.findRoute('mystatistics_contract');
			}
			return flag;
		},

		initData(obj, date) {
			this.choosed = obj;

			console.log('initData2');
			// return
			if (this.isShowDate) {
				this.chooseTime = JSON.parse(JSON.stringify(date));
				this.$refs['date-filter'].initDate({
					endTime: date.endTime,
					startTime: date.startTime,
					value: date.value,
				});
				this.$refs['date-filter2'].initDate({
					endTime: date.planEndDate || '',
					startTime: date.planBeginDate || '',
					value: date.value2 || '',
				});
			}
			if (this.orderType != null) {
				// this.$refs["date-other-filter"].initDate(this.dateObj);
			}
		},

		// 获取是否选中 type = 1 单个区分是否选中
		getChooseStatus(item, it, type) {
			let res = item.key;
			if (type === 1) {
				res = item;
			}
			if (this.choosed[res] && this.choosed[res].length > 0) {
				if (this.choosed[res].indexOf(it.value) != -1) {
					return true;
				}
			}
			return false;
		},

		// 选中某个标签
		chooseTag(key, it) {
			// 如果是全选全选关闭
			if (this.allChecked) {
				this.allChecked = false;
			}

			// 评分状态 单选
			if (key == 'scoreStatus') {
				if (this.choosed[key] && this.choosed[key].includes(it.value)) {
					delete this.choosed[key];
				} else {
					this.choosed[key] = [it.value];
				}
			} else if (this.choosed[key]) {
				let idx = this.choosed[key].indexOf(it.value);
				if (idx == -1) {
					this.choosed[key].push(it.value);
				} else {
					this.choosed[key].splice(idx, 1);
				}
			} else {
				this.choosed[key] = [it.value];
			}

			if (key == 'useTypes' && this.isMainPlan) {
				// 保养计划月历
				this.choosed[key] = [it.value];
			}
			this.$forceUpdate();

			this.$emit('chooseTag', {
				allChecked: this.allChecked,
				choosed: this.choosed,
				...this.chooseTime,
				// isActive:this.getChooseStatus(key, it,1)
			});
		},

		// 全选
		chooseAll() {
			this.choosed = {};
			// if(this.allChecked){
			// 	this.choosed={}
			// }
			this.allChecked = !this.allChecked;

			this.$emit('chooseTag', {
				allChecked: this.allChecked,
				choosed: this.choosed,
			});
		},

		// 确定
		async submit() {
			console.log(this.chooseTime, 'submit-this.chooseTime');
			let chooseTime = JSON.parse(JSON.stringify(this.chooseTime));
			this.$emit('submit', {
				allChecked: this.allChecked,
				choosed: this.choosed,
				parentArr: this.parentArr,
				keyMap: this.showMap,
				dateObj: chooseTime,
			});
		},

		clickstop() {
		},

		bindClose() {
			this.$emit('closed', 1);
		},

		// 标签点击更多
		showMore(e) {
			this.showMap[e.key].flag = !this.showMap[e.key].flag;
		},

		// 判断是否显示更多
		isShowMoreTag(list, key) {
			if (!Object.keys(this.showMap).length) {
				return;
			}
			let flag = false;
			if (list.length > 5) {
				flag = true;
				if (this.showMap[key].flag) {
					flag = true;
				}
			}
			return flag;
		},

		// 保养计划月历页面
		mianPlanReset(obj) {
			this.chooseTime.startTime = '';
			this.chooseTime.endTime = '';
			this.chooseTime.planBeginDate = '';
			this.chooseTime.planEndDate = '';
			this.chooseTime.value = '';
			this.chooseTime.value2 = '';
			this.$refs['date-filter2'].initDate(this.chooseTime);
			this.choosed[obj.key] = [obj.value];
			this.$forceUpdate();
		},

		// 保养计划月历页面
		defaultPlan(obj) {
			this.chooseTime.value2 = obj.value;
			this.$refs['date-filter2'].initDate(obj);
		},

		// 点击重置
		handleReset() {
			console.log('切换重置');

			if (this.isMainPlan) {
				this.$emit('defaultReset');
				return;
			}

			let len = Object.keys(this.choosed).length;
			if (len !== 0) {
				for (let key in this.choosed) {
					this.choosed[key] = [];
					this.$forceUpdate();
				}
				this.choosed = {};
			}
			if (this.allChecked) {
				this.allChecked = false;
			}
			this.chooseTime.startTime = '';
			this.chooseTime.endTime = '';
			this.chooseTime.planBeginDate = '';
			this.chooseTime.planEndDate = '';
			this.chooseTime.value = '';
			this.chooseTime.value2 = '';
			// console.log("重置");
			// 重置时间组件
			if (this.isShowDate) {
				this.$refs['date-filter'].initDate(this.chooseTime);
				this.$refs['date-filter2'].initDate(this.chooseTime);
			}
			if (this.isMainPlan) {
				this.$refs['date-filter2'].initDate(this.chooseTime);
			}

			// 重置模板组件
			if (this.isShowTemplate) {
				this.$refs['task-filter'].initData([]);
			}
			if (this.isShowPart) {
				// 重置配件组件
				this.$refs['pj-filter'].initData([]);
			}
			this.$emit('handleReset', {
				allChecked: false,
				choosed: this.choosed,
				reset: true,
			});
		},
	},
};
</script>

<style lang="scss" scoped>
.elevator-info {
  font-size: 28rpx;
  color: #666666;
  padding: 20rpx 32rpx;
  line-height: 1.6;

  .elevator-info-item {
    display: flex;
    align-items: center;
    margin-bottom: 10rpx;

    .elevator-icon {
      width: 32rpx;
      height: 32rpx;
      margin-right: 10rpx;
    }

    text {
      vertical-align: middle;
    }
  }
}
</style>
